package org.huzhp.security.wx;

import org.springframework.http.HttpMethod;
import org.springframework.security.authentication.AuthenticationServiceException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @Description 微信的鉴权过滤器，模仿 UsernamePasswordAuthenticationFilter 实现
 * @Author huzp
 * @Data 2019/3/28
 * @Version 1.0
 */
public class WxAuthenticationFilter extends AbstractAuthenticationProcessingFilter {
    /**
     * form表单中手机号码的字段name
     */

    public static final String SPRING_SECURITY_FORM_CODE_KEY = "code";

    public static final String SPRING_SECURITY_FORM_STATE_KEY = "state";
    /**
     * 是否仅 GET 方式
     */
    private boolean getOnly = true;

    public WxAuthenticationFilter() {
        super(new AntPathRequestMatcher(WxAuthenticationSecurityConfig.urlPath, HttpMethod.GET.name()));
    }

    @Override
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {
        if (getOnly && !request.getMethod().equals(HttpMethod.GET.name()) && request.getParameter(SPRING_SECURITY_FORM_CODE_KEY) == null) {
            throw new AuthenticationServiceException(
                    "Authentication method not supported: " + request.getMethod());
        }

        String code = obtainOauth2Code(request);

        String state = obtainOauth2State(request);

        WxAuthenticationToken authRequest = new WxAuthenticationToken(code, state);

        // Allow subclasses to set the "details" property
        setDetails(request, authRequest);

        return this.getAuthenticationManager().authenticate(authRequest);
    }

    protected String obtainOauth2Code(HttpServletRequest request) {
        return request.getParameter(SPRING_SECURITY_FORM_CODE_KEY);
    }

    protected String obtainOauth2State(HttpServletRequest request) {
        return request.getParameter(SPRING_SECURITY_FORM_STATE_KEY);
    }

    protected void setDetails(HttpServletRequest request, WxAuthenticationToken authRequest) {
        authRequest.setDetails(authenticationDetailsSource.buildDetails(request));
    }

    public void setGetOnly(boolean getOnly) {
        this.getOnly = getOnly;
    }
}
